<?php
namespace app\index\controller;

use app\index\model\Partner;
use think\Controller;
use app\index\model\Project;
use app\index\model\Member;
use app\index\model\Card;
use app\index\model\Recharge;
use app\index\model\Getcash;
use app\index\model\Putlog;
use app\index\model\Comgetcash;
use app\index\model\Mobilelog;
use app\index\Controller\DateTime;
use expand\Yunst;
use expand\YunPay;
use expand\YunBase;

class Yun extends Common
{
    public $cModel;
    public $CID;
    public $userId;
    public $bizUserId;

    public function _initialize(){
        parent::_initialize();
        if(!CheckMemberLogin()){
            return ajaxReturn('登录已过期');
        }
        $this->cModel = new Member();
        $this->userId = session('UID');
        $this->bizUserId = $this->cModel->where(['id'=>$this->userId])->value('bizUserId');
    }

    /**
     * 测试请求查询已绑卡的借口操作
     */

    public function queryBoundCard(){
        if(request()->isGet()){
            $YunClass = new Yunst();
            $bizUserId = 'hry13662200756';
            $res = $YunClass->boundCard($bizUserId,'');
            $data = json_decode($res['signedValue'],true);
            return $data;
        }
    }

    /**
     * 测试请求查询平台账户集余额
     */

    public function queryAccountInfo(){
        if(request()->isPost()){
            $YunClass = new Yunst();
            $account = '100004';
            $res = $YunClass->queryAccount($account);
            $data = json_decode($res['signedValue'],true);
            $data['allAmount']=number_format($data['allAmount']/100,2);
            $data['freezenAmount']=number_format($data['freezenAmount']/100,2);
            return $data;
        }
    }


    //请求绑定银行卡
    public function addCard(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            $CardModel = new Card();
            $data = input('post.');
            $info = [];
            if($data['cardType'] == 2){
//                $info['validate'] = $data['validate'];
//                $info['cvv2'] = $data['cvv2'];
                ajaxReturn('系统已禁止信用卡使用！');
            }
            $res = $YunClass->bindCard($this->bizUserId,$data['bank_number'],$data['bank_mobile'],$data['bank_truename'],$data['card'],$info);
            $data['date'] = date('Y-m-d H:i:s');
            if($res['status'] == 'OK'){
                unset($data['card']);
                $signedValue = json_decode($res['signedValue'],true);
                $data['user_id'] = $this->userId;
                $data['tranceNum'] = $signedValue['tranceNum']; //流水号
                $data['transDate'] = $signedValue['transDate'] ? $signedValue['transDate'] : date('Ymd'); //申请时间
                $data['bank_name'] = $signedValue['bankName']; //银行名称
                $data['bankCode'] = $signedValue['bankCode']; //银行代码
                $data['cardType'] = $signedValue['cardType']; //类型
                $InsetId = $CardModel->insertGetId($data);
                return ajaxReturn($InsetId,url('Member/card'));
            }elseif($res['errorCode']=='9000'){
                return ajaxReturn($res['message']);
            }else{
                return ajaxReturn($res['message']);
            }
        }
    }
    //确认绑定银行卡
    public function actCard(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            $CardModel = new Card();
            $id = input('post.id');
            $code = input('post.code');

            $CardInfo = $CardModel->where(['id'=>$id,'user_id'=>$this->userId])->find();
            if(empty($CardInfo)){
                return ajaxReturn('绑定失败');
            }
            $res = $YunClass->ActbindCard($this->bizUserId,$CardInfo,$code);
            $res['date'] = date('Y-m-d H:i:s');
            file_put_contents('actCard.txt',str_replace("\\", "", json_encode($res,JSON_UNESCAPED_UNICODE)).PHP_EOL,FILE_APPEND);
            if($res['status'] == 'OK'){
                $CardModel->where(['id'=>$id])->update(['status'=>1]);
                return ajaxReturn('绑定成功',url('Member/card'));
            }else{
                return ajaxReturn($res['message']);
            }
        }
    }

    //删除银行卡
    public function delCard(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            $CardModel = new Card();
            $id = input('post.id');
            $CardInfo = $CardModel->where(['id'=>$id,'user_id'=>$this->userId])->find();
            if(empty($CardInfo)){
                return ajaxReturn('删除失败');
            }

            if($CardInfo->getData('status') == 0){
                $res = $CardModel->where(['id'=>$id,'user_id'=>$this->userId])->delete();
                if($res){
                    return ajaxReturn('删除成功',url('Member/card'));
                }else{
                    return ajaxReturn($CardModel->getError());
                }
            }

            $res = $YunClass->unbindCard($this->bizUserId,$CardInfo['bank_number']);
            if($res['status'] == 'OK'){
                $CardModel->where(['id'=>$id,'user_id'=>$this->userId])->delete();
                return ajaxReturn('解绑成功',url('Member/card'));
            }else{
                return ajaxReturn($res['message']);
            }
        }
    }

//    //创建会员
//    public function createMember()
//    {
//        $YunClass = new Yunst();
//        $bizUserId = trim($_POST['bizUserId']);
//        $res = $YunClass->createMember($bizUserId);
//        halt($res);
//        if ($res['status'] == 'OK') {
//            $signedValue = json_decode($res['signedValue'], true);
//            return ajaxReturn($signedValue['cardBinInfo']['bankCode'], 1);
//        } else {
//            return ajaxReturn($res['message']);
//        }
//    }

    //查询银行卡
    public function getCardinfo(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            $cardNo = trim($_POST['cardNo']);
            $res = $YunClass->CardBin($cardNo);
            if($res['status'] == 'OK'){
                $signedValue = json_decode($res['signedValue'],true);
                return ajaxReturn($signedValue['cardBinInfo']['bankCode'],1);
            }else{
                return ajaxReturn($res['message']);
            }
        }
    }

    //发送云商短信
    public function SendYsCode(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            //$mobile = input('post.mobile');
            $mobile2 = input('post.newmobile');
            /*if($mobile2){
                $uid = $this->cModel->where(['yunmobile'=>$mobile2])->value('id');
                if($uid > 0){
                    return ajaxReturn('该手机已存在');
                }
                $mobile = $mobile2;
            }*/
            if(empty($mobile2)){
                return ajaxReturn('请填写新手机');
            }
            $res = $YunClass->sendVerifCode($this->bizUserId,$mobile2);
            if($res['status'] == 'OK'){
                return ajaxReturn('发送成功',1);
            }else{
                return ajaxReturn($res['message']);
            }
        }
    }
    //绑定手机
    public function bindMobile(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            $mobile = input('post.mobile');
            $code = input('post.code');
            $res = $YunClass->bindMobile($this->bizUserId,$mobile,$code);
            if($res['status'] == 'OK'){
                $this->cModel->where(['id'=>$this->userId])->update(['safeMobile'=>1,'yunmobile'=>$mobile]);
                return ajaxReturn('验证成功',url('Member/safe'));
            }else{
                return ajaxReturn($res['message']);
            }
        }
    }

    //发送解绑手机号短信
    public function SendUnbindMobileCode(){
        if(request()->isPost()){
        $YunClass = new Yunst();
        $mobile = input('post.mobile');
        if(empty($mobile)){
            ajaxReturn('请填写手机号');
        }
        $res = $YunClass->sendVerifCode($this->bizUserId,$mobile,6);
        if($res['status'] == 'OK'){
            ajaxReturn('发送成功',1);
        }else{
            ajaxReturn($res['message']);
        }
        }
    }


    //解绑手机
    public function unBindMobile(){
        if(request()->isPost()){
            $YunClass = new Yunst();
            $mobile = input('post.mobile');
            $code = input('post.code');
            if($mobile){
                $usermobile = $this->cModel->where(['mobile'=>$mobile,'id'=>['neq',$this->userId]])->value('mobile');
                if(!empty($usermobile)){
                    ajaxReturn('该手机已被其他用户作登录账号使用');
                }
            }
            $res = $YunClass->unBindMobile($this->bizUserId,$mobile,$code);
            if($res['status'] == 'OK'){
                $signedValue=json_decode($res['signedValue'],true);
                if($signedValue['result']=='OK'){
                    $this->cModel->where(['id'=>$this->userId])->update(['yunmobile'=>null,'safeMobile'=>0]);
                    ajaxReturn('验证成功',url('Member/safe'));
                }else{
                    ajaxReturn('验证失败');
                }

            }else{
                ajaxReturn($res['message']);
            }
        }
    }


    //更绑手机
    public function bindMobile2(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            $mobile = input('post.mobile');
            $mobile2 = input('post.newmobile');
            $code = input('post.code');
            if($mobile2){
                $usermobile = $this->cModel->where(['mobile'=>$mobile2,'id'=>['neq',$this->userId]])->value('mobile');
                if(!empty($usermobile)){
                    return ajaxReturn('该手机已被其他用户作登录账号使用');
                }
                $yunmobile = $this->cModel->where(['yunmobile'=>$mobile2])->value('yunmobile');
                if(!empty($yunmobile)){
                    return ajaxReturn('该手机已被认证');
                }
            }
            $res = $YunClass->bindMobile2($this->bizUserId,$mobile,$mobile2,$code);
            if($res['status'] == 'OK'){
                $this->cModel->where(['id'=>$this->userId])->update(['yunmobile'=>$mobile2]);
                return ajaxReturn('验证成功',url('Member/safe'));
            }else{
                return ajaxReturn($res['message']);
            }
        }
    }
    //支付密码
    public function SetPayPwd(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            $type = input('type');
            $data = $this->cModel->where(['id'=>$this->userId])->find();
            if($data['safeMobile'] == 0){
                return ajaxReturn('请先认证手机');
            }
            $url = $YunClass->setPayPass($this->bizUserId,$data,$type);
            return ajaxReturn('即将跳转',$url);
        }
    }
    //平台支付密码
    public function setPayPass(){
        if(request()->isAjax()){
            $pass = input('post.pwd');
            $code = input('post.code');
            $strlen=mb_strlen($code,'UTF8');
            if($strlen!=4){
                return ajaxReturn('手机验证码不正确');
            }
            if(session('paycode') != $code){
                return ajaxReturn('短信验证码不正确');
            }

            $res = $this->cModel->where(['id'=>$this->userId])->update(['pay_password'=>password_hash($pass,PASSWORD_DEFAULT)]);
            if($res){
                return ajaxReturn('设置成功',url('Member/safe'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }
    }

    //签约url
    public function QianYue(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            $url = $YunClass->QianYue($this->bizUserId);
            return ajaxReturn('即将跳转',$url);
        }
    }

    //提交充值申请
    public function createRorder(){
        if(request()->isAjax()){
            $CardModel = new Card();
            $RechargeModel = new Recharge();
            $MemberInfo = $this->cModel->where(['id'=>$this->userId])->find();
            if(empty($MemberInfo['pay_password'])){
                return ajaxReturn('未设置支付密码');
            }
            if(!password_verify(input('post.pwd'),$MemberInfo['pay_password'])){
                return ajaxReturn('支付密码不正确');
            }
            $CardInfo = $CardModel->where(['user_id'=>$this->userId,'id'=>input('post.bank')])->find();
            $money = input('post.money');
            if($money < confv('min-rechage')){
                return ajaxReturn('充值金额最低'.confv('min-rechage'));
            }
            $cvv=$CardInfo['cvv2'];
            if(!empty($cvv)){
                if($money>10000){
                    return ajaxReturn('信用卡单笔充值不得超过一万元');
                }else{
                    $date1=date("Y-m");
                    $date2=date("Y-m",strtotime("+1 months"));
                    $summoney=$RechargeModel->where(['user_id'=>$this->userId,'status'=>2,'iscvv'=>2])->where('date','between time',[$date1,$date2])->sum('money');
                    $sumcount=$RechargeModel->where(['user_id'=>$this->userId,'status'=>2,'iscvv'=>2])->where('date','between time',[$date1,$date2])->count();
                    $ssm=($money+$summoney);
                    if($summoney>=10000){
                        return ajaxReturn('信用卡充值金额已超过本月上限,请转用银行卡充值');
                    }elseif($ssm>10000){
                        return ajaxReturn('当次充值金额与累计金额相加超过本月上限,请转用银行卡充值');
                    }elseif($sumcount>=4){
                        return ajaxReturn('当月信用卡充值次数达到上限,请转用银行卡充值');
                    }
                }
                $iscvv=2;
            }else{
                $iscvv=1;
            }
            $fee = confv('fee');
            $feeto = $money < 200 ? 1 : round($fee / 100 * $money,2);
            $order = [
                'user_id' => $this->userId,
                'mobile'  => $CardInfo['bank_mobile'],
                'money'	=> $money,
                'fee'	=> $feeto,
                'order'	=> 'NO'.create_order(),
                'type'	=> 2,
                'status'=>0,
                'bankCardNo' => $CardInfo['bank_number'],
                'iscvv'=>$iscvv,
                'bankcard'=>$CardInfo['bank_number']
            ];

            $res = $RechargeModel->allowField(true)->save($order);
            if(!$res){
                return ajaxReturn($RechargeModel->getError());
            }
            $YunClass = new Yunst();
            $message = $YunClass->createRech($this->bizUserId,$order);  //云商通账户充值申请
            if($message['status'] != 'OK'){
                return ajaxReturn($message['message']);
            }
            $signedValue = json_decode($message['signedValue'],true);
            $RechargeModel -> where(['order'=>$signedValue['bizOrderNo']])->update(['status'=>1,'orderNo'=>$signedValue['orderNo'],'tradeNo'=>$signedValue['tradeNo']]);
            return ajaxReturn('请在三分钟内输入输入短信验证码',$signedValue['bizOrderNo']);
        }
    }

    //充值 - 确认支付
    public function surepay(){
        if(request()->isAjax()){
            $order = input('post.order');
            $code = input('post.code');
            $payClass = new Yunst();
            $RechargeModel = new Recharge();
            $tradeNo = $RechargeModel->where(['order'=>$order])->value('tradeNo');
            $res = $payClass->rechargePay($this->bizUserId,$order,$code,$tradeNo);
            if($res['status'] != 'OK'){
                return ajaxReturn($res['message']);
            }
            $signedValue = json_decode($res['signedValue'],true);
            if($signedValue['payStatus'] == 'fail'){
                return ajaxReturn('充值失败');
            }
            if($signedValue['payStatus'] == 'pending'){
                return ajaxReturn('充值进行中,请耐心等待');
            }
            return ajaxReturn('支付成功',url('Member/recharge'));
        }
    }

    //提现申请
    public function Tixian(){
        if(request()->isAjax()){
            $CashModel = new Getcash();
            $CardModel = new Card();
            $money = input('post.money');
            $MemberInfo = $this->cModel->where(['id'=>$this->userId])->find();
            if(empty($MemberInfo['pay_password'])){
                return ajaxReturn('未设置支付密码');
            }
            if(!password_verify(input('post.pwd'),$MemberInfo['pay_password'])){
                return ajaxReturn('支付密码不正确');
            }
            if($money<confv('min-getcash')){
                return ajaxReturn('不能少于'.confv('min-getcash'));
            }
            if($MemberInfo['money']<$money){
                return ajaxReturn('超过可提现额度');
            }
            $CardInfo = $CardModel->where(['user_id'=>$this->userId,'id'=>input('post.bank')])->find();
            $order = [
                'user_id' => $this->userId,
                'mobile'  => $CardInfo['bank_mobile'],
                'money'	  => $money,
                'fee'	  => confv('fee2'),
                'order'	  => 'GT'.create_order(),
                'card_id' => input('post.bank'),
                'status'  => 0,
                'bankCardNo' => $CardInfo['bank_number'],
                'date'	  => date('Y-m-d H:i:s')
            ];

            $res = $CashModel->allowField(true)->save($order);
            if(!$res){
                return ajaxReturn($CashModel->getError());
            }
            $msg = $this->cModel->where(['id'=>$this->userId])->update(['money'=>$MemberInfo['money']-$money]);
            if(!$msg){
                return ajax($this->cModel->getError());
            }
            $logModel = new Putlog();
            $log = [
                'uid' => $this->userId,
                'money' => -$money,
                'type'	=> 5, //提现
                'order'	=> 'OD'.create_order(),
                'status' => 1,
                'crate_time' => time()
            ];
            $logModel->allowField(true)->save($log);
            TobeNotice($this->userId, '提现通知', '您的提现申请已成功,请随时留意银行信息。');
            return ajaxReturn('提交成功,提现金额待后台审核通过后打入银行卡!',url('Member/index'));
        }
    }



    //网关支付
    public function getWayPay(){
        if(request()->isAjax()){
            $YunClass = new Yunst();
            $money = input('post.money');
            $bankCode = input('post.bankCode');
            if($money<confv('min-rechage')){
                return ajaxReturn('不能少于'.confv('min-rechage'));
            }
            $fee = confv('fee');
            $fee = $money < 200 ? 1 : round($fee / 100 * $money,2);
            $order = [
                'user_id' => $this->userId,
                'money'	=> $money,
                'fee'	=> $fee,
                'order'	=> 'NO'.create_order(),
                'type'	=> 1,
                'status'=>0,
                'bankCode'=>$bankCode
            ];
            $RechargeModel = new Recharge();
            $res = $RechargeModel->allowField(true)->save($order);
            if(!$res){
                return ajaxReturn($RechargeModel->getError());
            }
            $message = $YunClass->createRech2($this->bizUserId,$order);
            if($message['status'] != 'OK'){
                return ajaxReturn($message['message']);
            }
            $signedValue = json_decode($message['signedValue'],true);
            $RechargeModel -> where(['order'=>$signedValue['bizOrderNo']])->update(['status'=>1,'orderNo'=>$signedValue['orderNo']]);
            $payClass = new YunPay();
            $url = $payClass->surePay($this->bizUserId,$signedValue['bizOrderNo']);
            return ajaxReturn('即将跳转',$url);
        }
    }

    public function getPayCode(){
        if(request()->isAjax()){
            $data = $this->cModel->where(['id'=>$this->userId])->find();
            if(!captcha_check(input('post.txcode'))){
                return ajaxReturn('图形验证码不正确');
            }
            if($data['safeMobile'] == 0){
                return ajaxReturn('请先认证手机');
            }
            $code = rand(1000,9999);
            $res = SmsSend($data['yunmobile'],$code);
            if($res['code'] == 0){
                session('paycode',$code);
                return ajaxReturn('发送成功',url('Member/info'));
            }else{
                return ajaxReturn($res['detail']);
            }
        }
    }

    public function getfee(){
        if(request()->isAjax()){
            $money = input('money');
            $fee = confv('fee');
            if($money < 200){
                $res = 1;
            }else{
                $res = round($fee / 100 * $money,2);
            }
            return ajaxReturn($res,$res+$money);
        }
    }

//    public function zhuanzhang(){
//        $YunClass = new Yunst();
//        $bizUserId = 'hry18628223375';
//        $data['order_sn'] = 'zhuanzhang3211299937322';
//        $data['money'] = '10000';
//        $result = $YunClass->PingTaiZhuanZhang($bizUserId,$data);
//        echo '<pre/>';
//        print_r($result);exit;
//    }

//    //退款
//    public function refund(){
//        $YunClass = new Yunst();
//        $bizUserId = 'hry13559301168';
//        $orderNo = '3211299937';
//        $data['order'] = $orderNo;
//        $data['money'] = '26500';
//        $result = $YunClass->backOrderTo($bizUserId,$data);
//        echo '<pre/>';
//        print_r($result);exit;
//    }
//

    public function tixiana(){
        $YunClass = new Yunst();
        $message = $YunClass->TiMoney2();
        echo '<pre/>';
        print_r($message);exit;
    }

    public function toucun(){
        $YunClass = new Yunst();
        $message = $YunClass->queryReserve();
        echo '<pre/>';
        print_r($message);exit;
    }
}
